<template>
  <div>
    <div class="toolbar">
      <el-form :inline="true" :model="q" size="mini">
        <el-form-item label="日期">
          <el-date-picker v-model="q.time_range" value-format="yyyy-MM-dd" type="daterange" :picker-options="pickerOptions" :clearable="false" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="所属平台:">
          <more-selete v-if="MerchantsList.length" :dataList="MerchantsList" showName="name" v-model="q.mch_ids" placeholder="请选择"></more-selete>
        </el-form-item>
        <el-form-item label="所属总代:">
          <more-selete v-if="AgencyMainList.length" :dataList="AgencyMainList" showName="user_name" v-model="q.parent_ids" placeholder="请选择"></more-selete>
        </el-form-item>
        <el-form-item label="所属子代:">
          <more-selete v-if="AgencyList.length" :dataList="AgencyList" showName="user_name" v-model="q.agency_ids" placeholder="请选择"></more-selete>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="q.user_type" clearable placeholder="请选择">
            <el-option v-for="(type, index) of userType" :key="index" :label="type" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <!-- <el-button type="danger" @click="reload">重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-button size="mini" @click="downloadData" :type="downloading?'info':'primary'" :loading="downloading" icon="el-icon-printer" style="float: right">{{downloading?'导出中...':'导出报表'}}</el-button>
    </div>
    <el-table v-if="listData.items" :data="listData.items" v-loading.body="listLoading" @sort-change="sortlist" size="mini" :height="listData.total>25?'65vh':null" stripe border fit highlight-current-row>
      <el-table-column prop="day" label='日期' fixed="left" sortable="custom" width="110"></el-table-column>
      <el-table-column prop="mch_id" label='所属平台' fixed="left" min-width="140">
        <template slot-scope="scope">
          <span v-if="scope.row.mch_id=='-1'">汇总</span>
          <span v-else-if="MerchantsList.find(item=>item.id==scope.row.mch_id)">{{MerchantsList.find(item=>item.id==scope.row.mch_id)['name']}}</span>
        </template></el-table-column>
      <el-table-column prop="parent_id" label='所属总代' fixed="left" min-width="130">
        <template slot-scope="scope">
          <span v-if="scope.row.parent_id=='-1'">汇总</span>
          <span v-else-if="AgencyMainList.find(item=>item.id==scope.row.parent_id)">{{AgencyMainList.find(item=>item.id==scope.row.parent_id)['user_name']}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="agency_id" label='所属子代' fixed="left" min-width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.agency_id=='-1'">汇总</span>
          <span v-else-if="AgencyList.find(item=>item.id==scope.row.agency_id)">{{AgencyList.find(item=>item.id==scope.row.agency_id)['user_name']}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="agency_recharge_success_count" label='申请次数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="agency_recharge_success_amount" label='申请金额' sortable='custom' width="110">
        <template slot-scope="scope">{{(scope.row.agency_recharge_success_amount/100).toFixed(2)}}</template>
      </el-table-column>
      <el-table-column prop="user_recharge_create_count" label='发起人数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="user_recharge_create_times" label='发起次数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="user_recharge_success_count" label='充值人数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="user_recharge_success_times" label='充值次数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="user_recharge_success_amount" label='充值金额' sortable='custom' width="110">
        <template slot-scope="scope">{{(scope.row.user_recharge_success_amount/100).toFixed(2)}}</template>
      </el-table-column>
      <el-table-column prop="user_recharge_apply_rate" label='发起成功率' sortable='custom' width="130">
        <template slot-scope="scope">{{scope.row.user_recharge_apply_rate}}%</template>
      </el-table-column>
      <el-table-column prop="user_recharge_success_rate" label='订单成功率' sortable='custom' width="130">
        <template slot-scope="scope">{{scope.row.user_recharge_success_rate}}%</template>
      </el-table-column>
      <el-table-column prop="user_recharge_chase_count" label='追分次数' sortable='custom' width="120"></el-table-column>
      <el-table-column prop="user_recharge_chase_amount" label='追分金额' sortable='custom' width="120">
        <template slot-scope="scope">{{(scope.row.user_recharge_chase_amount/100).toFixed(2)}}</template>
      </el-table-column>
      <el-table-column prop="user_recharge_comment_count" label='评价次数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="user_recharge_good_comment_count" label='好评次数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="user_recharge_bad_comment_count" label='差评次数' sortable='custom' width="110"></el-table-column>
      <el-table-column prop="agency_complain_count" label='投诉次数' sortable='custom' width="110"></el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="q.page_no" :page-sizes="$store.state.app.pageSizeArr" :page-size="q.page_size" layout="total, sizes, prev, pager, next, jumper" :total="listData.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import MoreSelete from '@/components/MoreSelete/index'
import { getMerchantsList, getReportList, getAgencyList, exportExel } from '@/api'
// import { downloadDataToFile } from "../../utils/CommonJs";
import timedate from '@/utils/timedate.js'
import { setTimeout } from 'timers';
export default {
  components: { MoreSelete },
  data () {
    return {
      listData: {},
      // time_range: [timedate.dateWeek,timedate.dateToday],
      q: { page_size: 30, page_no: 1, sort_by: '-day', mch_ids: [], parent_ids: [], agency_ids: [], time_range: [timedate.dateWeek, timedate.dateToday],user_type:'' },
      listLoading: false,
      showUpdate: false,
      show_id: null,
      MerchantsList: [],
      AgencyMainList: [],
      AgencyList: [],
      userType: this.$store.state.app.userType,
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', timedate.dateToday);
          }
        }, {
          text: '昨天',
          onClick (picker) {
            picker.$emit('pick', timedate.dateYesterday);
          }
        }, {
          text: '一周前',
          onClick (picker) {
            picker.$emit('pick', timedate.dateWeek);
          },

        },
        {
          text: '最近一个月',
          onClick (picker) {
            picker.$emit('pick', timedate.dateOneMonth);
          }        }
        ]
      },
      dailyList: [],
      downloading: false
    }
  },
  activated () {
    this.getList()
    this.getMerchantsList()
    this.getAgencyList()
    this.getChildAgencyList()
  },
  deactivated () {
    this.listLoading = false
  },
  methods: {
    async downloadData () {
      this.downloading = true
      const taskres = await getReportList(Object.assign({}, this.q, { mch_ids: JSON.stringify(this.q.mch_ids), parent_ids: JSON.stringify(this.q.parent_ids), agency_ids: JSON.stringify(this.q.agency_ids), time_range: JSON.stringify(this.q.time_range), export: 1 }))
      if (taskres.status === 0) {
        this.exportExel(taskres.data.task_id)
      }
      // this.downloading = false
      // const tHeader = ['日期', '所属平台', '所属总代', '所属子代', '申请次数', '申请金额', '发起人数', '发起次数', '充值人数', '充值次数', '充值金额', '发起成功率', '订单成功率', '追分次数', '追分金额', '评价次数', '好评次数', '差评次数', '投诉次数'];
      // const filterVal = ['day', 'mch_id', 'parent_id', 'agency_id', 'agency_recharge_success_count', 'agency_recharge_success_amount', 'user_recharge_create_count', 'user_recharge_create_times', 'user_recharge_success_count', 'user_recharge_success_times', 'user_recharge_success_amount', 'user_recharge_apply_rate', 'user_recharge_success_rate', 'user_recharge_chase_count', 'user_recharge_chase_amount', 'user_recharge_comment_count', 'user_recharge_good_comment_count', 'user_recharge_bad_comment_count', 'agency_complain_count'];
      // downloadDataToFile(res, tHeader, filterVal, `报表管理${timedate.dateTodayHMS}`)
    },
    async exportExel (task_id) {
      const exportStatusRes = await exportExel(task_id)
      if (exportStatusRes.status === 0) {
        switch (exportStatusRes.data.status) {
          case 0:
            setTimeout(() => {
              this.exportExel(task_id)
            }, 1500)
            break
          case 1:
            window.location.href = `${window.location.origin}/export_data/${exportStatusRes.data.file_name}`
            this.downloading = false
            this.$message.success('导出成功')
            break;
          case 2:
              this.$message.info('导出失败')
              this.downloading = false
            break;
          case 3:
              this.$message.info('取消导出')
              this.downloading = false
            break;
        }
      }
    },
    getMerchantsList () {
      getMerchantsList().then(res => {
        if (res.status === 0) {
          this.MerchantsList = res.data.items
        }
      })
    },
    getAgencyList () {
      getAgencyList({ agency_type: 2, page_size: 1000 }).then(res => {
        if (res.status === 0) {
          this.AgencyMainList = res.data.items
        }
      })
    },
    getChildAgencyList () {
      getAgencyList({ agency_type: 1, page_size: 1000 }).then(res => {
        if (res.status === 0) {
          this.AgencyList = res.data.items
        }
      })
    },
    sortlist (sort) {
      if (sort.order === 'descending') {
        this.q.sort_by = '-' + sort.prop
      } else if (sort.order === 'ascending') {
        this.q.sort_by = sort.prop
      } else {
        this.q.sort_by = '-day'
      }
      this.getList()
    },
    add () {
      this.show_id = null
      this.showUpdate = true
    },
    update (row) {
      this.show_id = row.id
      this.showUpdate = true
    },
    remove () {
    },
    query () {
      this.q = Object.assign(this.q, { page_no: 1, page_size: 30 })
      this.getList()
    },
    reload () {
      this.q = { page_size: 30, page_no: 1, sort_by: '-day', mch_ids: [], parent_ids: [], agency_ids: [], time_range: [timedate.dateWeek, timedate.dateToday],user_type:'' }
      this.getList()
    },
    handleSizeChange (val) {
      this.q.page_size = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.q.page_no = val
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0
      this.getList()
    },
    getList () {
      getReportList(Object.assign({}, this.q, { mch_ids: JSON.stringify(this.q.mch_ids), parent_ids: JSON.stringify(this.q.parent_ids), agency_ids: JSON.stringify(this.q.agency_ids), time_range: JSON.stringify(this.q.time_range) })).then(res => {
        if (res.status === 0) {
          this.listData = {}
          this.listLoading = false
          this.listData = res.data
        }
      })
    }
  },
  watch: {
    showUpdate () {
      if (!this.showUpdate) {
        this.getList()
      }
    },
  }
}
</script>
